from turbogears import controllers, expose, flash, redirect, paginate
from model import *
from sqlobject.dberrors import DuplicateEntryError
from sqlobject.main import SQLObjectNotFound
from turbogears.widgets import DataGrid

import csv
import os
import datetime

# import logging
# log = logging.getLogger("wwwpayaso.controllers")

#SQLObjectNotFound:

add_photo_grid = DataGrid(
    fields=[
        DataGrid.Column('names', 'names', 'Names'),
        DataGrid.Column('disco', 'disco', 'Disco'),
        DataGrid.Column('date', 'date', 'Date'),
        DataGrid.Column('image', 'image', 'Image'),
        DataGrid.Column('thumbail', 'thumbail', 'Thumbail'),
    ])

class Root(controllers.RootController):
    disco_csv = "./wwwpayaso/static/csv/disco.csv"
    news_csv = "./wwwpayaso/static/csv/news.csv"

    @expose(template="wwwpayaso.templates.welcome")
    def index(self):
        import time
        # log.debug("Happy TurboGears Controller Responding For Duty")
        flash("Your application is now running")
        return dict(now=time.ctime())

    def update_disco(self):
        discos = csv.reader(open(self.disco_csv, "rb"), dialect="excel")
        for disco in discos:
            name, address, telephone, http, description, logo = disco
            try:
                Disco(name=name,
                      address=address,
                      telephone=telephone,
                      http=http,
                      description=description,
                      logo=logo)
            except DuplicateEntryError:
                pass

    def update_news(self):
        try:
            news = csv.reader(open(self.news_csv, "rb"), dialect="excel")
            for new in news:
                date, disco, short_description, long_description, title = new
                disco_id = Disco.selectBy(name=disco).getOne().id
                year, month, day = map(lambda x: int(x), date.split("-"))
                date_id = Date(date=datetime.date(year, month, day)).id
                News(date=date_id,
                     disco=disco_id,
                     short_description=short_description,
                     long_description=long_description,
                     title=title)
        except DuplicateEntryError, (strerror):
            pass

    @expose(template="wwwpayaso.templates.update_database")
    def update_database(self):
        """
        Actualiza la base de datos ingresando solo las fotos que no estan
        actualmente en la base de datos. Para esto comprueba la ultima fecha en
        la BD y la compara con la actual
        """
        path = "./wwwpayaso/static/images/photos"
        self.update_disco()
        self.update_news()
        add_photo_list = []
        for root, directories, files in os.walk(path):
            if directories == ["thumbails"]:
                # nombre de la disco
                disco_name = root.split("/")[-2]
                try:
                    # intento crearlo
                    disco_id = Disco(name=disco_name).id
                except DuplicateEntryError:
                    # si ya esta creado, tomo el id
                    disco_id = Disco.selectBy(name=disco_name).getOne().id
                # fecha
                date_values = root.split("/")[-1].split("-")
                year, month, day = map(lambda x: int(x), date_values)
                date = datetime.date(year, month, day)
                try:
                    date_id = Date(date=date).id
                except DuplicateEntryError:
                    date_id = Date.selectBy(date=date).getOne().id
                # path relativo
                relative_path = "/".join(root.split("/")[5:])
                for filename in files:
                    image = os.path.join(relative_path, filename)
                    thumbail = os.path.join(relative_path,"thumbails",filename)
                    try:
                        add_photo_list.append(Photo(names="",
                            disco=disco_id,
                            date=date_id,
                            image=image,
                            thumbail=thumbail))
                    except DuplicateEntryError:
                        pass
        count = len(add_photo_list)
        return dict(photos=add_photo_list,
                    photo_list=add_photo_grid,
                    count=count,
                    now=datetime.datetime.ctime(datetime.datetime.today()))

    @expose(template="wwwpayaso.templates.show_photos")
    @paginate("photos")
    def show_photos(self):
        """
        Consulta la BD sobre las fotos que se deben mostrar en la pagina web, y
        devuelve una lista de fotos. Luego el paginador de TurboGears se
        encarga de separar la consulta de a DEFAULT=10 fotos
        """
        photos = Photo.select()
        return dict(photos=photos)